/**
 * 显示对象选择工具
 */

import { Drawer, List, Button } from "antd";
import Controller from 'Controller';
import IElement from 'components/Three/interface/IElement';
import * as THREE from 'three';
import React from "react";

export interface ISelectElementProps {
    visible: boolean;
    onClose?: () => void;
    onSelect?: (uuid: string) => void;
    filter?: (e: IElement<THREE.Object3D>) => boolean
}

export default function SelectElement(props: ISelectElementProps) {

    const { visible, onClose, filter } = props;

    const threeController = Controller.instance.useMemo(s => s.threeController, []);

    const elementMap = threeController.useMemo(s => s.elementMap, []);

    const scene = threeController.useMemo(s => s.scene, []);

    const dataSource = React.useMemo(() => {
        if (!scene) return [];

        return scene.children.map(e => elementMap.get(e.uuid) as IElement<THREE.Object3D>).filter(e => {
            if (!!e) {
                return filter ? filter(e) : true;
            } else {
                return false;
            }
        })
    }, [elementMap, filter, scene])

    const onClickListItem = React.useCallback((uuid: string) => {
        props.onSelect && props.onSelect(uuid);
    }, [props])

    if (!scene) return <></>;

    return (
        <Drawer title="选择显示对象" placement="right" onClose={onClose} visible={visible}>
            <List
                bordered
                dataSource={dataSource}
                renderItem={item => {
                    return (
                        <List.Item>
                            <Button type="link" onClick={() => { onClickListItem(item.object3D.uuid) }} >
                                {item.object3D.name || item.object3D.uuid}
                            </Button>
                        </List.Item>
                    )
                }}
            />
        </Drawer>
    )
}